const fs = require('fs')
const fileService = require('../service/File.service')
const MomentService = require('../service/Moment.service')
const { PICTURE_PATH } = require('../constants/file-path')

class MomentContraller {
  async publicMoment(ctx, next) {
    const userId = ctx.user.id
    const { content } = ctx.request.body
    const result = await MomentService.publicMoment(userId, content)
    ctx.body = result
  }

  // 根据id获取moment
  async detail(ctx, next) {
    const { momentId } = ctx.request.params
    const result = await MomentService.getMomentById(momentId)
    ctx.body = result
  }

  async list(ctx, next) {
    // 获取查询数量
    const { offset, size } = ctx.request.query
    // 从数据库查询相应数量的数据
    const result = await MomentService.getMomentList(offset, size)
    ctx.body = result
  }

  async updateMoment(ctx, next) {
    const { momentId } = ctx.params
    const { content } = ctx.request.body
    const result = await MomentService.updateMoment(momentId, content)
    ctx.body = result
  }
  async deleteMoment(ctx, next) {
    const { momentId } = ctx.params
    const result = await MomentService.deleteMoment(momentId)
    ctx.body = result
  }

  async addLabel(ctx, next) {
    const { labels } = ctx
    const { momentId } = ctx.params
    for (const label of labels) {
      // 查看动态和标签关系表中是否已经存在记录
      const isExist = await MomentService.hasLabel(momentId, label.id)
      if (!isExist) {
        await MomentService.addLabel(momentId, label.id)
      }
    }
    ctx.body = '添加标签成功'
  }
  async fileInfo(ctx, next) {
    let { filename } = ctx.params
    const fileInfo = await fileService.getFileByFilename(filename)
    const { type } = ctx.query
    console.log(type);

    const types = ['small', 'middle', 'large']
    if (types.some((item) => item === type)) {
      filename = filename + '-' + type
    }

    // 返回图片
    ctx.response.set('content-type', fileInfo.mimetype)
    ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
  }
}

module.exports = new MomentContraller()
